package command

import (
	"context"

	"gitee.com/crack007/goose/gscore"
	"gitee.com/crack007/goose/gsutil"
	"github.com/spf13/cobra"
)

type CmdBuilder struct {
	gscore.BaseBuilder
	iCmdHandle ICmdHandle
	Graceful   bool
}

func NewCmdBuilder(iCmdHandle ICmdHandle) *CmdBuilder {
	ctx, cancelFunc := context.WithCancel(context.Background())
	return &CmdBuilder{
		BaseBuilder: gscore.BaseBuilder{
			CobraCmd:   &cobra.Command{},
			Ctx:        ctx,
			CancelFunc: cancelFunc,
		},
		iCmdHandle: iCmdHandle,
	}
}

func (x *CmdBuilder) Build() (gscore.IServer, error) {
	cmdInstance := &Cmd{
		Builder: x,
		handle:  x.iCmdHandle,
		BaseServer: gscore.BaseServer{
			Ctx:      x.GetCtx(),
			Cancel:   x.GetCancelFunc(),
			WorkPath: gsutil.RuntimeUtil.GetWorkPath(),
		},
		graceful: x.Graceful,
	}
	cmdInstance.WorkPath = gsutil.RuntimeUtil.GetWorkPath()
	cmdInstance.SetCobraCmd(x.GetCobraCmd())
	return cmdInstance, nil
}

func (x *CmdBuilder) GetHandle() gscore.IHandle {
	return x.iCmdHandle
}

func (x *CmdBuilder) EnableGraceful() *CmdBuilder {
	x.Graceful = true
	return x
}
